package net.scdx.hotel.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import net.scdx.hotel.entity.User;
import net.scdx.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/verifycode")
public class CodeController {
    private static final long serialVersionUID = 1L;
    //短信平台相关参数

    private String apiUrl = "https://sms_developer.zhenzikj.com";
    //榛子云系统上获取
    private String appId = "101947";
    private String appSecret = "6d8e85bb-36b2-4db6-96e9-99afa935bbb0";

    @Autowired
    private UserService userService;

    @ResponseBody
    @GetMapping("/get_code")
    public Map<String,Object > getCode(@RequestParam("username") String username, @RequestParam("memPhone") String memPhone, HttpSession httpSession) throws Exception {
        Map<String,Object> modelMap = new HashMap<>();
        User member = userService.userInfo(username);
        if (member!=null &&
                member.getUsername().equals(username) &&
                member.getTel().equals(memPhone)){
            try {
                JSONObject json = null;
                //随机生成验证码
                String code = String.valueOf(new Random().nextInt(999999));
                //将验证码通过榛子云接口发送至手机
                ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
                String result = client.send(memPhone, "您的验证码为:" + code + "");

                json = JSONObject.parseObject(result);
                if (json.getIntValue("code")!=0){//发送短信失败
                    modelMap.put("success", false);
                    modelMap.put("data", json.getString("data"));
                    return modelMap;
                }
                // 将认证码存入SESSION
                httpSession.setAttribute("code",code);

                modelMap.put("success", true);
                modelMap.put("data", json.getString("data"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return modelMap;
    }
}